package node;

import java.net.InetAddress;
import java.util.concurrent.LinkedBlockingQueue;

import task.IQueue;
import event.EQueue;
import event.Event;

public class NodeManageThread extends Thread implements NodeManageWorkerListener{
	protected EQueue 		theQueue; 
	protected InetAddress 	discoveryAddress;
	protected int 			discoveryPort;
	protected LinkedBlockingQueue<Runnable>	workerPool;
	private	IQueue			taskQueue;
	private Node 			node;
	
	private boolean			pauseThread;
	
	public NodeManageThread(EQueue realQueue, InetAddress discoveryAddress, int discoveryPort, IQueue taskQueue, Node node)
	{
		super("NodeManageThread");
		theQueue 				= realQueue;
		this.discoveryAddress 	= discoveryAddress;
		this.discoveryPort 		= discoveryPort; 
		
		workerPool				= new LinkedBlockingQueue<Runnable>();
		
		this.taskQueue			= taskQueue;
		this.node 				= node;
		
		pauseThread				= false;	
	}
	
	public void setPauseThread(boolean newValue)
	{
		this.pauseThread = newValue;
	}
	
	@Override
	public void run() {
		// TODO Auto-generated method stub
		while(true)
		{
			Event currentEvent = theQueue.dequeue();
			if(currentEvent != null && workerPool.size() < NodeDescriptor.getInstance().getEMaxThreads())
			{
				NodeManageWorker eventWorker = new NodeManageWorker(currentEvent, discoveryAddress, discoveryPort, taskQueue,this.node);
				eventWorker.workerDelegate = this;
				workerPool.add(eventWorker);
				new Thread(eventWorker, "NodeManageWorker").start();
			}
			
			synchronized(this)
			{
				while(this.pauseThread)
				{
					try{
						this.wait();
					} catch(InterruptedException e) {}
				}		
			}
		}
	}

	@Override
	public synchronized void workerHasFinished(NodeManageWorker w) {
		// TODO Auto-generated method stub
		this.workerPool.remove(w);
	}
}
